/* 格式化报价商品addon */
Vue.directive('parsing-addon', function (el, binding) {
        var addon = binding.value;
        try {
            if (typeof JSON.parse(addon) == "object"){
                var jsonObj = JSON.parse(addon);
                var content = '';
                for (var a in jsonObj){
                    var partsName = jsonObj[a].partsName;
                    var text = partsName + '：';
                    var basicParam = jsonObj[a].basicParam;
                    if (!isBlank(basicParam)){
                        for (var b in basicParam){
                            text += ' ' + basicParam[b];
                        }
                    }
                    var craftParam = jsonObj[a].craftParam;
                    if (!isBlank(craftParam)){
                        for (var c in craftParam){
                            text += ' ' + craftParam[c];
                        }
                    }if (a == jsonObj.length - 1){
                        content += text
                    }else {
                        content += text + '，'
                    }
                }
                el.textContent = content;
                return
            }
        }catch (e){}
        el.textContent = addon
    })

/* 商品类型为印刷、快印商品，从addon中获取数量 */
Vue.directive('parsing-num', function (el, binding) {
        var item = binding.value
        var nums = item.nums
        try {
            if (typeof JSON.parse(item.addon) == "object"){
                var jsonObj = JSON.parse(item.addon);
                for (var a in jsonObj){
                    var basicParam = jsonObj[a].basicParam;
                    if (!isBlank(basicParam)){
                        for (var b in basicParam){
                            if (b == '数量'){
                                nums = basicParam[b]
                                break
                            }
                        }
                    }
                }
            }
        }catch (e){}
        el.textContent = nums
    })

var vm = new Vue({
    el:'#rrapp',
    data:{
        showList: true,
        designerLoading: false,
        /* 实体类 */
        orderInfo: {},
        orderServicer: {},
        erpOrder: {},
        orderItemList: [],
        orderItem: {},
        orderRemarks: [],
        erpOrderLogs: [],
        orderLogs: [],
        userBaseInfos: [],
        receiptsAccounts: [],
        userPaymentList: [],
        erpOrderProductionEntityList:[],//生产信息
        orderLogisticsEntityList:[],//物流信息
        username: '',
        /* 共用 */
        pub: {
            orderId: '',
            remark: ''
        },
        /* 枚举 */
        e:{
            payTypeEnum: [],
            goodsTypeEnum:[],
            orderInfoStatusEnum:[],
            thirdMerchantTypeEnum:[],
            taxTypeEnum:[],
            taxContentEnum: [
                {text: '订单明细'},
                {text: '印刷品'},
                {text: '纸制品'},
                {text: '设计费'},
                {text: '铜版纸'},
                {text: '双胶纸'},
                {text: '白卡纸'},
                {text: '复印纸'},
                {text: '淋膜纸'}
            ],
        },
        /* 查询 */
        q:{
            orderId: '',
            parentOrderId: '',
            memberName: '',
            status: 'active',
            orderType: '',
            beginCreatetime: '',
            endCreatetime: '',
            auditStatus: '0',
            payStatus: '',
            shipName:'',
            shipTel:'',
            supplierType: '',// 订单所属 0：紫云网  1：第三方
            paymentId:'',
            isquery: false,
        },
        /* 订单支付字段 */
        pay:{
            bank: '',
            account: '',
            money: '',
            payName: '',
            memo: '',
            tPayed: '',
            payAppId: '',
        },
        /* 订单商品审核字段 */
        itemAuditVisible: false,
        audit:{
            desigener: '',
            approvalStatus: '',
            remark: '',
        },
        /* 省市区data */
        options: [],
        /* 省市区回显 */
        areaCascader: [],
        /* 商品文件上传 */
        formLabelWidth: '120px',
        fileTableVisible: false,
        itemFile:{
            /* 保证 $.files_up_oss 在当前页面只初始化一次 */
            filesUpOss: false,
            /* 订单商品集合下标标识，获得当前正在操作的商品元素 */
            itemIndex: 0,
            /* 正在操作商品的附件集合 */
            itemFiles: []
        },
        /* 收货人信息 */
        shipForm:{
            shipTime: '',
            shipName: '',
            shipMobile: '',
            shipAddr: '',
            shipZip: '',
            sendType: '',
            costFreight: '',
            areaCascader: '',
            shipAreaId: '',
            shipArea: ''
        },
        shipFormVisible: false,
        /* 订单调价 */
        costForm: {
            discount: '',
            remark: ''
        },
        costFormVisible: false,
        /* 发票信息修改*/
        invoiceFrom:{
            taxType:'',
            taxIdentification:'',
            taxContent:'',
            taxAddr:'',
            taxCompany:'',
            taxTel:'',
            taxAccountName:'',
            taxNumber:'',
        },
        /* 送货单是否开发票 */
        taxForm: {
            orderId: '',
            sendTax: 0
        },
        /* 修改发票信息 重置按钮 */
        invoiceFormVisible:false,
        resetForm(invoiceFrom) {
            this.$refs[invoiceFrom].resetFields();
        },
        /* 修改商品信息 */
        itemForm: {
            itemId: null,
            name: null,
            price: null,
            nums: null,
            amount: null
        }
    },
    methods: {
        /* 支付时间 */
        checkPayDate: function () {
            WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss',isShowClear:false, onpicking:function (dp) {
                    vm.pay.tPayed = dp.cal.getNewDateStr();
                }})
        },
        /* 订单起始 */
        checkBeginDate: function () {
            WdatePicker({dateFmt:'yyyy-MM-dd',isShowClear:false, onpicking:function (dp) {
                    vm.q.beginCreatetime = dp.cal.getNewDateStr();
                }})
        },
        /* 订单结束 */
        checkEndDate: function () {
            WdatePicker({dateFmt:'yyyy-MM-dd',isShowClear:false, onpicking:function (dp) {
                    vm.q.endCreatetime = dp.cal.getNewDateStr();
                }})
        },
        /* 获取当前日期 */
        dateFormat:function(date) {
            if (typeof date == 'string'){
                date = new Date(date);
            }else if (typeof date == 'undefined'){
                date = new Date();
            }
            var year = date.getFullYear();
            var month = date.getMonth()+1<10 ? "0"+(date.getMonth()+1) : date.getMonth()+1;
            var day = date.getDate()<10 ? "0"+date.getDate() : date.getDate();
            var hours = date.getHours()<10 ? "0"+date.getHours() : date.getHours();
            var minutes = date.getMinutes()<10 ? "0"+date.getMinutes() : date.getMinutes();
            var seconds = date.getSeconds()<10 ? "0"+date.getSeconds() : date.getSeconds();
            return year+"-"+month+"-"+day+" "+hours+":"+minutes+":"+seconds;
        },
        /* 银行账户 */
        receiptsAccountsChange: function (event) {
            var idx = event.target.value;
            vm.pay.bank = vm.receiptsAccounts[idx].fraBank;
            vm.pay.account = vm.receiptsAccounts[idx].fraAccount.split('-')[0];
        },
        /* 支付方式 */
        payTypeChange: function () {
            var payAppId = vm.pay.payAppId;
            var data = vm.e.payTypeEnum.find((item) => {
                return item.value == payAppId;
            });
            vm.pay.payName = data.describe;
        },
        /* 获取当前登陆人信息 */
        getUserInfo: function () {
            $.get(baseURL + "sys/user/info", function(r){
                vm.username = r.user.username;
            });
        },
        /* 订单详情 */
        getInfo: function (orderId) {
            $.get(baseURL + "order/orderinfo/info/" + orderId, function(r){
                /* 数据 */
                vm.orderInfo = r.orderInfo;
                vm.orderItemList = r.orderItemList;
                vm.userPaymentList = r.userPaymentList;
                vm.receiptsAccounts = r.receiptsAccounts;
                /* 枚举 */
                vm.e.payTypeEnum = r.payTypeEnum;
                vm.e.goodsTypeEnum = r.goodsTypeEnum;
                vm.e.thirdMerchantTypeEnum = r.thirdMerchantTypeEnum;
                vm.e.taxTypeEnum = r.taxTypeEnum;

                $.get(baseURL + "order/orderinfo/getOrderLogfo/" + orderId, function(r1){
                    vm.orderServicer = r1.orderServicer;
                    vm.orderRemarks = r1.orderRemarks;
                    vm.erpOrderLogs = r1.erpOrderLogs;
                    vm.orderLogs = r1.orderLogs;
                });
                $.get(baseURL + "order/orderinfo/getOrderProduction/" + orderId, function(r2){
                    vm.erpOrderProductionEntityList = r2.erpOrderProductionEntityList;
                });
                $.get(baseURL + "order/orderinfo/getOrderLogi/" + orderId, function(r3){
                    vm.orderLogisticsEntityList = r3.orderLogisticsEntityList;
                });
                // 编辑回显级联省市区
                $.get(baseURL + "freightages/sdbectoolsregions/queryRegionsSascade", function(r4){
                    vm.options = JSON.parse(r4.list);
                });
                vm.showList = false;
                vm.filesUploadInit();
            });
        },
        /* 商品详情（报价计算过程） */
        showItemDetail: function (item) {
            window.itemQuoteDetailVm.loadData({
                itemId: item.itemId,
                goodsType: item.goodsType,
                name: item.name
            })
        },
        /* 获取设计师信息 */
        getDesignerData: function (val) {
            var self = this;
            self.designerLoading = true;
            $.get(baseURL + "order/orderinfo/getOrderDesigner?name=" + val, function(r){
                self.userBaseInfos = r.userBaseInfos;
                self.designerLoading = false;
            });
        },
        /* 上传文件初始化 */
        filesUploadInit: function () {
            Vue.nextTick(function () {
                // DOM 更新后 初始化oss文件上传
                if (vm.itemFile.filesUpOss){
                    return false;
                }
                vm.itemFile.filesUpOss = true;

                var ids = [];
                var len = vm.orderItemList.length;
                for (var i = 0; i < len; i++){
                    ids.push("upload" + i);
                }

                /* oss上传 */
                $.files_up_oss({
                    id: ids,// 按钮id
                    url: "/sys/oss/getSignature",
                    dir: "order/orderimage/",
                    file_type: "jpg,png,gif,psd,ai,cdr,eps,ppt,word,excel,pdf,tiff,rar,zip,7z",
                    size: "2000mb",//mb
                    view_url: window.parent.vm.ossHost
                }, function (index_number, json) {
                    console.info('files_up_oss[index_number:' + index_number + '],[json:'+ JSON.stringify(json) +']');
                    if (json.Status == 'OK'){
                        var orderItem = vm.orderItemList[index_number];
                        var name = json.oldFilename.replace(/'/g, '');
                        var userAccessory = {
                            orderId: vm.orderInfo.orderId,
                            itemId: orderItem.itemId,
                            userId: vm.orderInfo.userId,
                            url: json.filename,
                            name: name,
                            size: json.size,
                            fileType: json.mimeType
                        }

                        $.ajax({
                            type: "POST",
                            url: baseURL + "order/useraccessory/save",
                            contentType: "application/json",
                            data: JSON.stringify(userAccessory),
                            success: function(r){
                                if(r.code === 0){
                                    vm.getInfo(vm.orderInfo.orderId);
                                }else{
                                    alert(r.msg);
                                }
                            }
                        });
                    }else {
                        alert("OSS上传失败，请联系后台管理员！");
                    }
                });
            })
        },
        /* 订单作废 */
        orderInvalid: function (orderId) {
            vm.pub.orderId = orderId;
            layer.open({
                type: 1,
                skin: 'layui-layer-molv',
                title: "订单作废",
                area: ['550px', '280px'],
                shadeClose: false,
                scrollbar: false,
                content: jQuery("#remarksLayer"),
                btn: ['保存','取消'],
                btn1: function (index) {
                    $.ajax({
                        type: "GET",
                        url: baseURL + "order/orderinfo/orderInvalid",
                        contentType: "application/json",
                        data: {
                            'orderId': orderId,
                            'remarks': vm.pub.remark
                        },
                        success: function(r){
                            if(r.code == 0){
                                layer.close(index);
                                alert('操作成功', function(index){
                                    vm.getInfo(vm.orderInfo.orderId);
                                    vm.pub.remark = '';
                                    vm.pub.orderId = '';
                                });
                            }else{
                                alert(r.msg);
                            }
                        }
                    });
                },
                btn2: function (index) {
                    layer.close(index);
                    vm.pub.remark = '';
                    vm.pub.orderId = '';
                }
            });
        },
        /* 快捷订单作废（后台人员使用） */
        orderQuickInvalid: function (orderId) {
            vm.pub.orderId = orderId;
            layer.open({
                type: 1,
                skin: 'layui-layer-molv',
                title: "订单作废",
                area: ['550px', '280px'],
                shadeClose: false,
                scrollbar: false,
                content: jQuery("#remarksLayer"),
                btn: ['保存','取消'],
                btn1: function (index) {
                    $.ajax({
                        type: "GET",
                        url: baseURL + "order/orderinfo/orderQuickInvalid",
                        contentType: "application/json",
                        data: {
                            'orderId': orderId,
                            'remarks': vm.pub.remark
                        },
                        success: function(r){
                            if(r.code == 0){
                                layer.close(index);
                                alert('操作成功', function(index){
                                    vm.getInfo(vm.orderInfo.orderId);
                                    vm.pub.remark = '';
                                    vm.pub.orderId = '';
                                });
                            }else{
                                alert(r.msg);
                            }
                        }
                    });
                },
                btn2: function (index) {
                    layer.close(index);
                    vm.pub.remark = '';
                    vm.pub.orderId = '';
                }
            });
        },
        /* 订单完成 */
        orderFinish: function (orderId) {
            vm.pub.orderId = orderId;
            layer.open({
                type: 1,
                skin: 'layui-layer-molv',
                title: "订单完成",
                area: ['550px', '280px'],
                shadeClose: false,
                content: jQuery("#remarksLayer"),
                btn: ['保存','取消'],
                btn1: function (index) {
                    $.ajax({
                        type: "GET",
                        url: baseURL + "order/orderinfo/orderFinish",
                        contentType: "application/json",
                        data: {
                            'orderId': orderId,
                            'remarks': vm.pub.remark
                        },
                        success: function(r){
                            if(r.code == 0){
                                layer.close(index);
                                alert('操作成功', function(index){
                                    vm.getInfo(vm.orderInfo.orderId);
                                    vm.pub.remark = '';
                                    vm.pub.orderId = '';
                                });
                            }else{
                                alert(r.msg);
                            }
                        }
                    });
                },
                btn2: function (index) {
                    layer.close(index);
                    vm.pub.remark = '';
                    vm.pub.orderId = '';
                }
            });
        },
        /* 订单备注 */
        orderRemark: function (orderId) {
            vm.pub.orderId = orderId;
            layer.open({
                type: 1,
                skin: 'layui-layer-molv',
                title: "订单备注",
                area: ['550px', '280px'],
                shadeClose: false,
                content: jQuery("#remarksLayer"),
                btn: ['保存','取消'],
                btn1: function (index) {
                    $.ajax({
                        type: "GET",
                        url: baseURL + "order/orderinfo/orderRemarks",
                        contentType: "application/json",
                        data: {
                            'orderId': orderId,
                            'remarks': vm.pub.remark
                        },
                        success: function(r){
                            if(r.code == 0){
                                layer.close(index);
                                vm.pub.remark = '';
                                vm.pub.orderId = '';
                                vm.reload();
                            }else{
                                alert(r.msg);
                            }
                        }
                    });
                },
                btn2: function (index) {
                    layer.close(index);
                    vm.pub.remark = '';
                    vm.pub.orderId = '';
                }
            });
        },
        /* 是否开发票 */
        orderTax: function (orderId, sendTax) {
            vm.taxForm.orderId = orderId;
            vm.taxForm.sendTax = sendTax;
            layer.open({
                type: 1,
                skin: 'layui-layer-molv',
                title: "送货单是否开发票",
                area: ['550px', '250px'],
                shadeClose: false,
                content: jQuery("#taxLayer"),
                btn: ['保存','取消'],
                btn1: function (index) {
                    $.ajax({
                        type: "GET",
                        url: baseURL + "order/orderinfo/orderTax",
                        contentType: "application/json",
                        data: {
                            'orderId': vm.taxForm.orderId,
                            'sendTax': vm.taxForm.sendTax
                        },
                        success: function(r){
                            if(r.code == 0){
                                layer.close(index);
                                vm.taxForm.orderId = '';
                                vm.taxForm.sendTax = 0;
                                vm.reload();
                            }else{
                                alert(r.msg);
                            }
                        }
                    });
                },
                btn2: function (index) {
                    layer.close(index);
                    vvm.taxForm.orderId = '';
                    vm.taxForm.sendTax = 0;
                }
            });
        },
        /* 商品审核 */
        orderItemAudit: function () {
            if (vm.orderItem.goodsType == 'design' && isBlank(vm.audit.desigener)){
                alert("请选择设计师！");
                return;
            }
            if (isBlank(vm.audit.approvalStatus)){
                alert("请勾选审核通过按钮！");
                return;
            }
            var postData = {
                'orderId': vm.orderItem.orderId,
                'itemId': vm.orderItem.itemId,
                'goodsType': vm.orderItem.goodsType,
                'desigener': vm.audit.desigener,
                'approvalStatus': vm.audit.approvalStatus,
                'remark': vm.audit.remark,
            }
            $.ajax({
                type: "POST",
                url: baseURL + "order/orderitem/orderItemAudit",
                contentType: "application/json",
                data: JSON.stringify(postData),
                success: function(r){
                    if(r.code == 0){
                        alert('操作成功', function(){
                            vm.getInfo(vm.orderItem.orderId);
                            vm.audit.approvalStatus = '';
                            vm.audit.desigener = '';
                            vm.audit.remark = '';
                            vm.itemAuditVisible = false;
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        /* 商品审核页面 */
        orderItemAuditShow: function (idx) {
            var orderItem = vm.orderItemList[idx];
            vm.orderItem = orderItem;
            $('#remark').val('');
            vm.itemAuditVisible = true;
        },
        /* 申请售后 */
        applyService: function () {
            // 跳转申请售后页面
            if (vm.orderInfo.orderId){
                window.registerDialogVm.loadData({orderId:vm.orderInfo.orderId});
            }else {
                this.$message({
                    message: '等待页面加载!',
                    type: 'warning'
                });
            }
        },
        /* 订单支付 */
        orderPay: function () {
            // 设置当前时间
            vm.pay.tPayed = vm.dateFormat();
            vm.getUserInfo();
            layer.open({
                type: 1,
                skin: 'layui-layer-molv',
                title: "订单支付",
                area: ['700px', '650px'],
                shadeClose: false,
                scrollbar: false,
                content: jQuery("#orderPayLayer"),
                btn: ['保存','取消'],
                btn1: function (index) {
                    var postData = {
                        orderId: vm.orderInfo.orderId,
                        account: vm.pay.account,
                        bank: vm.pay.bank,
                        money: vm.pay.money,
                        payName: vm.pay.payName,
                        memo: vm.pay.memo,
                        paymentTime: vm.pay.tPayed,
                        payAppId: vm.pay.payAppId
                    }
                    $.ajax({
                        type: "POST",
                        url: baseURL + "order/orderinfo/orderPayment",
                        contentType: "application/json",
                        data: JSON.stringify(postData),
                        success: function(r){
                            if(r.code == 0){
                                layer.close(index);
                                alert('操作成功', function(index){
                                    vm.pay.bank = '';
                                    vm.pay.money = '';
                                    vm.pay.payAppId = '';
                                    vm.pay.payName = '';
                                    vm.pay.memo = '';
                                    vm.pay.tPayed = '';
                                    vm.getInfo(vm.orderInfo.orderId);
                                });
                            }else{
                                alert(r.msg);
                            }
                        }
                    });
                }
            });
        },
        /* 展示收货人信息 */
        openShipForm: function () {
            // 复制属性值
            vm.shipForm = Object.assign({}, vm.orderInfo);
            var regionPath = vm.orderInfo.regionPath;
            var sendType = vm.orderInfo.pickUp == true ? '1' : '0';
            Vue.set(vm.shipForm, 'sendType', sendType);
            // 回显省市区
            if (!isBlank(regionPath)){
                // 字符型数组
                var regionPathStringArr = regionPath.substring(1, regionPath.length-1).split(",");
                // 整形数组
                var regionPathIntArr = regionPathStringArr.map(function(data){
                    return + data;
                });
                vm.shipForm.areaCascader = regionPathIntArr;
            }
            vm.shipFormVisible = true;
        },
        /* 修改收货人信息 */
        changeShipInfo: function () {
            vm.erpOrder = new Object();
            vm.erpOrder.orderNo = vm.orderInfo.orderId;
            vm.erpOrder.shipName = vm.shipForm.shipName;
            vm.erpOrder.shipMobile = vm.shipForm.shipMobile;
            vm.erpOrder.shipAddr = vm.shipForm.shipAddr;
            vm.erpOrder.shipZip = vm.shipForm.shipZip;
            vm.erpOrder.sendType = vm.shipForm.sendType;
            vm.erpOrder.costFreight = vm.shipForm.costFreight;
            vm.erpOrder.shipAreaId = vm.shipForm.shipAreaId;
            vm.erpOrder.shipArea = vm.shipForm.shipArea;

            $.ajax({
                type: "POST",
                url: baseURL + "order/erporder/orderReceiverUpdate",
                contentType: "application/json",
                data: JSON.stringify(vm.erpOrder),
                success: function(r){
                    vm.shipFormVisible = false;
                    if(r.code === 0){
                        vm.getInfo(vm.orderInfo.orderId);
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        /* 修改费用信息 */
        changeCost: function () {
            var discount = vm.costForm.discount;
            if (discount == ''){
                alert("调价不能为空");
                return false;
            }
            var remark = vm.costForm.remark;
            if (isBlank(remark)){
                alert("改价原因不能为空");
                return false;
            }

            $.ajax({
                type: "GET",
                url: baseURL + "order/orderinfo/orderDiscountAudit",
                contentType: "application/json",
                data: {
                    'orderId': vm.orderInfo.orderId,
                    'discount': discount,
                    'remark': remark
                },
                success: function(r){
                    vm.costFormVisible = false;
                    if(r.code === 0){
                        vm.costForm.discount = '';
                        vm.costForm.remark = '';
                        vm.getInfo(vm.orderInfo.orderId);
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        /* 省市区 */
        handleItemChange: function (val) {
            var values = val.join(',').split(',');
            var areaId = values[val.length - 1];
            vm.shipForm.shipAreaId = areaId;

            var lableVal = getCascaderObj(val, vm.options);
            var area = lableVal.join(',').replace(new RegExp(',', 'g'), ' ');
            vm.shipForm.shipArea = area;
        },
        /* 显示发票信息 */
        openInvoiceFrom:function(){
            // 复制属性值
            vm.invoiceFrom = Object.assign({}, vm.orderInfo);
            vm.invoiceFormVisible = true; //加载数据开启窗口
        },
        /* 修改发票信息 */
        changeTaxInfo(invoiceFrom){
            var  postData = {
                orderId: vm.orderInfo.orderId,
                userId: vm.orderInfo.userId,
                taxType: vm.invoiceFrom.taxType,
                taxIdentification:vm.invoiceFrom.taxIdentification,
                taxContent:vm.invoiceFrom.taxContent,
                taxCompany:vm.invoiceFrom.taxCompany,
                taxAddr:vm.invoiceFrom.taxAddr,
                taxTel:vm.invoiceFrom.taxTel,
                taxAccountName:vm.invoiceFrom.taxAccountName,
                taxNumber:vm.invoiceFrom.taxNumber,
            }
            this.$refs[invoiceFrom].validate((valid) => {
                if (valid) {
                    //   做出判断，提交地址
                    var url;
                    if(isBlank(vm.orderInfo.taxType)){
                        url = "order/ordertax/save";
                    } else{
                        url = "order/ordertax/update";
                    }

                    $.ajax({
                        type: "POST",
                        url: baseURL + url,
                        contentType: "application/json",
                        data: JSON.stringify(postData),
                        success: function(r){
                            vm.invoiceFormVisible=false;  //关闭弹出窗口
                            if(r.code === 0){
                                vm.getInfo(vm.orderInfo.orderId);
                            }else{
                                alert(r.msg);
                            }
                        }
                    });

                } else {
                    console.log('error primary!!');
                    return false;
                }
            });
        },
        /* 展示商品文件 */
        itemFileShow: function (idx) {
            var itemId = vm.orderItemList[idx].itemId;
            $.ajax({
                type: "GET",
                url: baseURL + "order/useraccessory/userAccessorys/" + itemId,
                contentType: "application/json",
                data: [],
                success: function(r){
                    if(r.code === 0){
                        var goodsName = vm.orderItemList[idx].name;
                        vm.fileTableVisible = true;
                        vm.itemFile.itemIndex = idx;
                        vm.itemFile.itemFiles = r.list;
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        /* 商品原文件下载 */
        itemSourceFileDownload: function (data) {
            window.location.href = baseURL + "order/useraccessory/download/" + data.id;
        },
        /* 商品发货文件下载 */
        itemSendFileDownload: function (data) {
            window.location.href = baseURL + "otherAccessory/otheraccessory/download/" + data.id;
        },
        /* 商品文件删除 */
        itemFileDelete: function (data) {
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                callback: function (f) {
                    if (f == 'confirm'){
                        var ids = [data.id];
                        $.ajax({
                            type: "POST",
                            url: baseURL + "order/useraccessory/delete",
                            contentType: "application/json",
                            data: JSON.stringify(ids),
                            success: function(r){
                                if(r.code === 0){
                                    vm.getInfo(vm.orderInfo.orderId);
                                    vm.itemFileShow(vm.itemFile.itemIndex);
                                }else{
                                    alert(r.msg);
                                }
                            }
                        });
                    }
                }
            })
        },
        /* 订单标记异常 */
        adnormal: function(orderId){
            confirm('确定要将当前订单标记为异常订单？', function(){
                $.ajax({
                    type: "GET",
                    url: baseURL + "order/orderinfo/adnormal",
                    contentType: "application/json",
                    data: {
                        'orderId': orderId
                    },
                    success: function(r){
                        if(r.code == 0){
                            alert('操作成功', function(index){
                                vm.reload();
                            });
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        /* 企业集采商品价格更新 */
        itemPriceChange: function () {
            this.itemForm.amount = Math.floor(this.itemForm.price * this.itemForm.nums * 100) / 100;
        },
        /* 企业集采商品修改 */
        itemUpdate: function (idx) {
            var item = vm.orderItemList[idx];
            this.itemForm.itemId = item.itemId;
            this.itemForm.name = item.name;
            this.itemForm.price = item.price;
            this.itemForm.nums = item.nums;
            this.itemForm.amount = item.amount;
            layer.open({
                type: 1,
                skin: 'layui-layer-molv',
                title: "修改商品信息",
                area: ['600px', '330px'],
                shadeClose: false,
                content: jQuery("#orderItemLayer"),
                btn: ['保存','取消'],
                btn1: function (index) {
                    var postData = {
                        orderId: vm.orderInfo.orderId,
                        itemId: vm.itemForm.itemId,
                        price: vm.itemForm.price,
                        nums: vm.itemForm.nums,
                        amount: vm.itemForm.amount,
                    }
                    $.ajax({
                        type: "POST",
                        url: baseURL + "production/erporderitem/procurementItemUpdate",
                        contentType: "application/json",
                        data: JSON.stringify(postData),
                        success: function(r){
                            if(r.code == 0){
                                layer.close(index);
                                alert('操作成功', function(index){
                                    vm.getInfo(vm.orderInfo.orderId);
                                });
                            }else{
                                alert(r.msg);
                            }
                        }
                    });
                }
            });
        },
        /* 重置筛选 */
        reset: function () {
            vm.q.orderId = '';
            vm.q.parentOrderId = '';
            vm.q.memberName = '';
            vm.q.status = '';
            vm.q.orderType = '';
            vm.q.beginCreatetime = '';
            vm.q.endCreatetime = '';
            vm.q.auditStatus = '';
            vm.q.payStatus = '';
            vm.q.supplierType = '';
            vm.q.paymentId = '';
            vm.q.isquery = true;
            vm.reload();
        },
        query: function () {
            vm.q.isquery = true;
            vm.reload();
        },
        reload: function (event) {
            vm.showList = true;
            var isquery = vm.q.isquery;
            var page = $("#jqGrid").jqGrid('getGridParam','page');
            if (isquery){
                page = 1;
            }
            vm.q.isquery = false;
            $("#jqGrid").jqGrid('setGridParam',{
                page: page,
                postData:{
                    'orderId': vm.q.orderId,
                    'parentOrderId': vm.q.parentOrderId,
                    'memberName': vm.q.memberName,
                    'status': vm.q.status,
                    'orderType': vm.q.orderType,
                    'beginCreatetime': vm.q.beginCreatetime,
                    'endCreatetime': vm.q.endCreatetime,
                    'auditStatus': vm.q.auditStatus,
                    'payStatus': vm.q.payStatus,
                    'shipName':vm.q.shipName,
                    'shipTel':vm.q.shipTel,
                    'supplierType':vm.q.supplierType,
                    'paymentId':vm.q.paymentId
                },
            }).trigger("reloadGrid");
        }
    },
    mounted: function () {
        $("#jqGrid").jqGrid({
            url: baseURL + 'order/orderinfo/list',
            datatype: "json",
            colModel: [
                { label: '操作', name: 'operation',  width: 60 , align:'center',title:false,
                    formatter:function(value, options, row){
                        var html = '<li class="dropdown" style="list-style: none;position: absolute;width: 60px;right: auto;left: auto;"><a href="#" style="margin:0 auto;text-decoration:none;" class="dropdown-toggle" data-toggle="dropdown">操作</a>';
                        html += '<ul class="dropdown-menu"  style="min-width:100%;font-size: 12px;">';
                        var operations = [];
                        if (row.status == 'active'){
                            operations.push('<li><a href="javascript:;" onclick="return vm.orderInvalid(\''+ options.rowId +'\');">作废</a></li><li class="divider"></li>');
                            operations.push('<li><a href="javascript:;" onclick="return vm.adnormal(\''+ options.rowId +'\');">异常</a></li><li class="divider"></li>');
                        }
                        operations.push('<li><a href="javascript:;" onclick="return vm.orderRemark(\''+ options.rowId +'\');">备注</a></li><li class="divider"></li>');
                        operations.push('<li><a href="javascript:;" onclick="return vm.orderTax(\''+ row.orderId +'\', \''+ row.sendTax +'\');">是否开发票</a></li>');
                        html += operations.join("")
                        html += '</ul></li>';
                        return html;
                    }
                },
                { label: '订单编号', name: 'orderId', index: 'order_Id', width: 120, key: true , align:'center',
                    formatter: function (value, options, row) {
                        return '<a href="javascript:;" onclick="return vm.getInfo(\''+ options.rowId +'\');">'+ row.orderId +'</a></li>';
                    }
                },
                { label: '父单号', name: 'parentOrderId', index: 'parent_order_id', width: 120, align:'center'},
                { label: '会员名', name: 'memberName', index: '', width: 150 , align:'center'},
                { label: '订单总额', name: 'payableAmount', index: 'payable_amount', width: 80 , align:'center'},
                { label: '订单状态', name: 'status', index: 'status', width: 80 , align:'center',
                    formatter: function (value, options, row) {
                        var valueText = "";
                        var userData = $("#" + options.gid).jqGrid('getGridParam', 'userData');
                        $.each(userData.orderInfoStatusEnum, function (index, module) {
                            if (module.value == value) {
                                valueText = module.describe;
                                return false;
                            }
                        });
                        return valueText;
                    }},
                { label: '平台来源', name: 'source', index: 'source', width: 80 , align:'center'},
                { label: '下单时间', name: 'createtime', index: 'createtime', width: 120 , align:'center'},
                { label: '支付状态', name: 'payStatus', index: 'pay_status', width: 80 , align:'center',
                    formatter: function (value, options, row) {
                        return value == '1' ? '已支付' : '未支付';
                    }},
                { label: '审核状态', name: 'productionStatusText', index: '', width: 80 , align:'center',
                    formatter: function (value, options, row) {
                        if (value != '待审核' && value != '异常单'){
                            return '已审核';
                        }
                        return value;
                    }},
                { label: '支付信息', name: 'payInfo', width: 120 , align:'center'},
                { label: '收货人', name: 'shipName', index: 'ship_name', width: 80 , align:'center'},
                { label: '收货电话', name: 'shipMobile', width: 80 , align:'center'},
                { label: '客服备注人', name: 'remarkName', width: 120 , align:'center'},
                { label: '客户留言', name: 'memo', index: 'memo', width: 120 , align:'center'},
            ],
            postData:{
                'orderId': this.q.orderId,
                'memberName': this.q.memberName,
                'status': this.q.status,
                'orderType': this.q.orderType,
                'beginCreatetime': this.q.beginCreatetime,
                'endCreatetime': this.q.endCreatetime,
                'auditStatus': this.q.auditStatus,
                'payStatus': this.q.payStatus,
                'shipName':this.q.shipName,
                'shipTel':this.q.shipTel,
                'supplierType':this.q.supplierType,
            },
            viewrecords: true,
            height: window.innerHeight - 120,
            rowNum: 25,
            rowList : [25,50,75],
            rownumbers: true,
            rownumWidth: 40,
            autowidth:true,
            multiselect: false,
            pager: "#jqGridPager",
            jsonReader : {
                root: "page.list",
                page: "page.currPage",
                total: "page.totalPage",
                records: "page.totalCount",
                userdata: "userData"
            },
            prmNames : {
                page:"page",
                rows:"limit",
                order: "order"
            },
            gridComplete:function(){
                //隐藏grid底部滚动条
                $("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
                //枚举参数
                var userData = $("#jqGrid").jqGrid('getGridParam', 'userData');
                vm.e.orderInfoStatusEnum = userData.orderInfoStatusEnum;
            }
        });
        // 显示序号
        $("#jqGrid").jqGrid('setLabel',0, '序号', '{width:80}');
    }
});

/**
 * 省市区级联选择
 * @param val
 * @param opt
 */
function getCascaderObj(val, opt) {
    return val.map(function (value, index, array) {
        for (var itm in opt) {
            if (opt[itm].value == value) {
                var label = opt[itm].label;
                opt = opt[itm].children; return label;
            }
        }
        return null;
    });
}
